package com.mojian.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mojian.common.RedisConstants;
import com.mojian.entity.ResourceDownload;
import com.mojian.entity.SysResource;
import com.mojian.enums.ResourceStatusEnum;
import com.mojian.exception.ServiceException;
import com.mojian.mapper.ResourceDownloadMapper;
import com.mojian.mapper.SysResourceMapper;
import com.mojian.service.PointsService;
import com.mojian.service.ResourceService;
import com.mojian.utils.PageUtil;
import com.mojian.utils.RedisUtil;
import com.mojian.vo.resource.ResourceDownloadVo;
import com.mojian.vo.resource.SysResourceVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * @author: quequnlong
 * @date: 2025/3/12
 * @description:
 */
@Service
@RequiredArgsConstructor
public class ResourceServiceImpl implements ResourceService {

    private final SysResourceMapper baseMapper;
    private final ResourceDownloadMapper resourceDownloadMapper;
    private final RedisUtil redisUtil;
    private final PointsService pointsService;

    @Override
    public Page<SysResourceVo> getResourceList(SysResource sysResource) {
        if (sysResource.getPageNum() == null) {
            sysResource.setPageNum(1);
        }
        if (sysResource.getPageSize() == null) {
            sysResource.setPageSize(10);
        }
        return baseMapper.getResourceList(new Page<>(sysResource.getPageNum(), sysResource.getPageSize()), sysResource);
    }

    @Override
    public void add(SysResource sysResource) {
        sysResource.setUserId(StpUtil.getLoginIdAsLong());
        sysResource.setStatus(ResourceStatusEnum.AUDIT.getCode());
        sysResource.setDownloads(0);
        sysResource.setPointsEarned(0);
        baseMapper.insert(sysResource);
    }

    @Override
    public SysResource verify(String code, Long id) {
        String key = RedisConstants.CAPTCHA_CODE_KEY + code;
        if (!redisUtil.hasKey(key)) {
            throw new ServiceException("验证码错误");
        }
        redisUtil.delete(key);

        SysResource sysResource = baseMapper.selectById(id);
        if (sysResource == null) {
            throw new ServiceException("资源不存在");
        }

        sysResource.setDownloads(sysResource.getDownloads() + 1);
        baseMapper.updateById(sysResource);

        return sysResource;
    }
    
    @Override
    public SysResourceVo getResourceDetail(Long id) {
        // 使用自定义查询获取包含用户信息的资源详情
        SysResource param = new SysResource();
        param.setId(id);
        
        Page<SysResourceVo> page = baseMapper.getResourceList(new Page<>(1, 1), param);
        if (page.getRecords().isEmpty()) {
            throw new ServiceException("资源不存在");
        }
        
        SysResourceVo resourceVo = page.getRecords().get(0);
        
        // 日志输出，检查资源类型
        System.out.println("获取资源详情: ID=" + resourceVo.getId() + 
                           ", 名称=" + resourceVo.getName() + 
                           ", 类型=" + resourceVo.getType() + 
                           ", 积分=" + resourceVo.getPoints() + 
                           ", 网盘地址=" + resourceVo.getPanPath() + 
                           ", 提取码=" + resourceVo.getPanCode());
        
        // 如果某些关键字段为null，从原始表中获取
        if (resourceVo.getPanPath() == null || resourceVo.getPanCode() == null || 
            resourceVo.getType() == null || resourceVo.getPoints() == null) {
            
            System.out.println("资源详情存在null字段，尝试从原始表获取完整数据");
            SysResource originalResource = baseMapper.selectById(id);
            if (originalResource != null) {
                if (resourceVo.getPanPath() == null) resourceVo.setPanPath(originalResource.getPanPath());
                if (resourceVo.getPanCode() == null) resourceVo.setPanCode(originalResource.getPanCode());
                if (resourceVo.getType() == null) resourceVo.setType(originalResource.getType());
                if (resourceVo.getPoints() == null) resourceVo.setPoints(originalResource.getPoints());
                if (resourceVo.getPrice() == null) resourceVo.setPrice(originalResource.getPrice());
                if (resourceVo.getDescription() == null) resourceVo.setDescription(originalResource.getDescription());
                
                System.out.println("补充后的资源详情: 类型=" + resourceVo.getType() + 
                                  ", 积分=" + resourceVo.getPoints() + 
                                  ", 网盘地址=" + resourceVo.getPanPath());
            }
        }
        
        return resourceVo;
    }
    
    @Override
    public boolean checkDownloadPermission(Long resourceId) {
        Long userId = StpUtil.getLoginIdAsLong();
        SysResource resource = baseMapper.selectById(resourceId);
        
        if (resource == null) {
            throw new ServiceException("资源不存在");
        }
        
        // 如果是自己上传的资源，直接有权限
        if (resource.getUserId().equals(userId)) {
            return true;
        }
        
        // 如果是免费资源，直接有权限
        if (resource.getType() == 1) {
            return true;
        }
        
        // 如果是积分资源，检查是否已经兑换过
        if (resource.getType() == 2) {
            Long count = resourceDownloadMapper.selectCount(
                new LambdaQueryWrapper<ResourceDownload>()
                    .eq(ResourceDownload::getUserId, userId)
                    .eq(ResourceDownload::getResourceId, resourceId)
            );
            return count != null && count > 0;
        }
        
        // 如果是付费资源，暂不处理
        return false;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean exchangeResource(Long resourceId) {
        Long userId = StpUtil.getLoginIdAsLong();
        SysResource resource = baseMapper.selectById(resourceId);
        
        if (resource == null) {
            throw new ServiceException("资源不存在");
        }
        
        // 检查是否是积分资源
        if (resource.getType() != 2) {
            throw new ServiceException("该资源不是积分资源");
        }
        
                 // 检查是否已经兑换过
         Long count = resourceDownloadMapper.selectCount(
             new LambdaQueryWrapper<ResourceDownload>()
                 .eq(ResourceDownload::getUserId, userId)
                 .eq(ResourceDownload::getResourceId, resourceId)
         );
         
         if (count != null && count > 0) {
            throw new ServiceException("您已经兑换过该资源");
        }
        
        // 检查积分是否足够
        if (!pointsService.hasEnoughPoints(userId, resource.getPoints())) {
            throw new ServiceException("积分不足");
        }
        
        // 扣除积分
        pointsService.consumePoints(
            userId, 
            resource.getPoints(), 
            3, // 类型3表示下载资源
            resourceId, 
            "下载资源：" + resource.getName()
        );
        
        // 记录下载
        ResourceDownload download = new ResourceDownload();
        download.setUserId(userId);
        download.setResourceId(resourceId);
        download.setPoints(resource.getPoints());
        resourceDownloadMapper.insert(download);
        
        // 资源上传者获得70%的积分奖励
        int rewardPoints = (int)(resource.getPoints() * 0.7);
        if (rewardPoints > 0) {
            pointsService.addPoints(
                resource.getUserId(), 
                rewardPoints, 
                2, // 类型2表示上传资源获得积分
                resourceId, 
                "资源被下载奖励：" + resource.getName()
            );
            
            // 更新资源获得的积分
            resource.setPointsEarned(resource.getPointsEarned() + rewardPoints);
            baseMapper.updateById(resource);
        }
        
        return true;
    }
    
    @Override
    public String getDownloadUrl(Long resourceId) {
        Long userId = StpUtil.getLoginIdAsLong();
        SysResource resource = baseMapper.selectById(resourceId);
        
        if (resource == null) {
            throw new ServiceException("资源不存在");
        }
        
        // 检查下载权限
        if (!checkDownloadPermission(resourceId)) {
            throw new ServiceException("您没有权限下载该资源");
        }
        
        // 更新下载次数
        resource.setDownloads(resource.getDownloads() + 1);
        baseMapper.updateById(resource);
        
        // 返回下载链接（网盘地址和提取码）
        return resource.getPanPath() + "?pwd=" + resource.getPanCode();
    }
    
    @Override
    public Page<SysResourceVo> getMyResources(Integer pageNum, Integer pageSize, String name) {
        Long userId = StpUtil.getLoginIdAsLong();
        
        SysResource queryParam = new SysResource();
        queryParam.setUserId(userId);
        queryParam.setName(name);
        
        return baseMapper.getResourceList(new Page<>(pageNum, pageSize), queryParam);
    }
    
    @Override
    public Page<ResourceDownloadVo> getMyDownloads(Integer pageNum, Integer pageSize) {
        Long userId = StpUtil.getLoginIdAsLong();
        Page<ResourceDownloadVo> page = new Page<>(pageNum, pageSize);
        return resourceDownloadMapper.getMyDownloads(page, userId);
    }
    
    @Override
    public boolean deleteResource(Long resourceId) {
        Long userId = StpUtil.getLoginIdAsLong();
        SysResource resource = baseMapper.selectById(resourceId);
        
        if (resource == null) {
            throw new ServiceException("资源不存在");
        }
        
        // 检查是否是自己的资源
        if (!resource.getUserId().equals(userId)) {
            throw new ServiceException("您只能删除自己上传的资源");
        }
        
        return baseMapper.deleteById(resourceId) > 0;
    }
}
